package zhang.lao.console.controller.wn.map;/**
 * Created by zhangqin on 2017/8/29.
 */

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zhang.lao.build.mybatis.jdbc.auto.model.*;
import zhang.lao.build.tool.ListUtils;
import zhang.lao.build.tool.PathKit;
import zhang.lao.build.tool.date.DateStyle;
import zhang.lao.build.tool.date.DateUtil;
import zhang.lao.service.console.MachineMonitoringService;
import zhang.lao.service.console.PointRespService;
import zhang.lao.dao.base.*;
import zhang.lao.pojo.console.ConsoleContext;
import zhang.lao.pojo.console.map.PointResp;
import zhang.lao.pojo.console.req.GetAutoMachineTraceReq;
import zhang.lao.pojo.console.resp.HttpResult;
import zhang.lao.pojo.console.resp.HttpResultUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 农机监控
 *
 * @author
 * @create 2017-08-29 9:19
 **/

@Controller
public class MachineMonitoringController {
    private final static Logger logger = LoggerFactory.getLogger(MachineMonitoringController.class);

    @Autowired
    private WnLnglatAutomaticNewDao wnLnglatAutomaticNewDao;
    @Autowired
    private MachineMonitoringService machineMonitoringService;
    @Autowired
    private WnMachineDeviceActiveDao wnMachineDeviceActiveDao;
    @Autowired
    private PointRespService pointRespService;

    @Autowired
    private WnMachineDeviceDao wnMachineDeviceDao;
    @Autowired
    private WnFarmDao wnFarmDao;

    /**
     * 根据角度及类型获取监控图片
     * @param response
     * @param degree
     * @param name
     */
    @RequestMapping("/console/machine/monitoring/image/{name}@{degree}")
    public void getMachineImage(HttpServletResponse response, @PathVariable int degree, @PathVariable String name){
        OutputStream outputStream=null;
        try {
            outputStream=response.getOutputStream();
            String path = PathKit.getWebRootPath()+ File.separator+"static"+ File.separator+"image"+ File.separator+"map"+ File.separator+name;
            machineMonitoringService.getMonitoringImage(path,degree,outputStream);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally{
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 获取自动驾驶坐标
     * @return
     */
    @RequestMapping("/console/machine/monitoring/page")
    public String autoMachinePage(ConsoleContext consoleContext,ModelMap modelMap){
        List<String> farms = consoleContext.getFarms();
        StringBuffer stringBuffer = new StringBuffer();
        if(farms!=null){
            for (String farm : farms) {
                WnFarm wnFarm = wnFarmDao.selectByPrimaryKey(farm);
                String name = wnFarm.getName();
                String id = wnFarm.getId();
                stringBuffer.append(" <input checked type='checkbox' value='"+id+"' lay-filter=\"farmId\" title='"+name+"'>");

            }
        }
        modelMap.put("farms",stringBuffer.toString());
        if(consoleContext.isPhone()){
            return "console/map/phone/auto_monitoring";
        }
        return "console/map/auto_monitoring";
    }

    /**
     * 获取自动驾驶坐标
     * @return
     */
    @RequestMapping("/console/machine/monitoring/ponit/json")
    public @ResponseBody HttpResult autoMachinePoints(String farmId,ConsoleContext consoleContext){

        List<WnLnglatAutomaticNew> wnLnglatMachineNews = wnLnglatAutomaticNewDao.selectByExample(null);
        List<PointResp> pointResps = new ArrayList<>();
        if(wnLnglatMachineNews!=null){
            for (WnLnglatAutomaticNew wnLnglatMachineNew : wnLnglatMachineNews) {
                WnMachineDeviceExample wnMachineDeviceExample = new WnMachineDeviceExample();
                List<String> framids = consoleContext.getFarms();
                if (StringUtils.isNotBlank(farmId)) {
                    framids = Lists.newArrayList(farmId.split(","));
                }
                wnMachineDeviceExample.createCriteria().andFarmIdIn(framids).andIdEqualTo(wnLnglatMachineNew.getDeviceId());
                int count = wnMachineDeviceDao.countByExample(wnMachineDeviceExample);
                if (count > 0) {
                    PointResp pointResp = pointRespService.buildAutoMachine(wnLnglatMachineNew);
                    pointResps.add(pointResp);
                }
            }
        }
        return HttpResultUtil.buildSuccess(pointResps);
    }


    /**
     * 获取自动驾驶轨迹页面
     * @return
     */
    @RequestMapping("/console/machine/monitoring/trace/page")
    public String autoMachineTracePage(String deviceId, ModelMap modelMap,ConsoleContext consoleContext){
        modelMap.put("deviceId",deviceId);
        WnMachineDeviceActiveExample wnMachineDeviceActiveExample = new WnMachineDeviceActiveExample();

        WnMachineDeviceActiveExample wnMachineDeviceActiveExample1 = new WnMachineDeviceActiveExample();
        wnMachineDeviceActiveExample1.createCriteria().andDeviceIdEqualTo(Integer.parseInt(deviceId));
        wnMachineDeviceActiveExample1.setOrderByClause("create_time desc");
        WnMachineDeviceActive first = ListUtils.getFirst(wnMachineDeviceActiveDao.selectByExample(wnMachineDeviceActiveExample1));
        Date date = first.getCreateTime();
        wnMachineDeviceActiveExample.createCriteria().andCreateDateBetween(DateUtil.getBeforeDate(30,date),date).andDeviceIdEqualTo(Integer.parseInt(deviceId));
        wnMachineDeviceActiveExample.setOrderByClause("create_time desc");
        List<WnMachineDeviceActive> wnMachineDeviceActives = wnMachineDeviceActiveDao.selectByExample(wnMachineDeviceActiveExample);
        StringBuffer stringBuffer = new StringBuffer("{");
        if(wnMachineDeviceActives!=null&&wnMachineDeviceActives.size()>0){
            modelMap.put("date",DateUtil.DateToString(wnMachineDeviceActives.get(0).getCreateDate(), DateStyle.YYYY_MM_DD));

            for (int i = 0; i < wnMachineDeviceActives.size(); i++) {
                Date createDate = wnMachineDeviceActives.get(i).getCreateDate();
                if(i==wnMachineDeviceActives.size()-1){
                    stringBuffer.append("'"+DateUtil.DateToString(createDate,DateStyle.YYYY_MM_DD)+"':'"+DateUtil.DateToString(createDate,DateStyle.DD)+"'");
                }else {
                    stringBuffer.append("'" + DateUtil.DateToString(createDate, DateStyle.YYYY_MM_DD) + "':'"+DateUtil.DateToString(createDate,DateStyle.DD)+"',");
                }
            }

        }else{

        }
        stringBuffer.append("}");
        modelMap.put("dates",stringBuffer);
        if(consoleContext.isPhone()){
            return "console/map/phone/auto_monitoring_trace";
        }
        return "console/map/auto_monitoring_trace";
    }

    /**
     * 获取精准时间段Gt06轨迹页面
     * @return
     */
    @RequestMapping("/console/machine/monitoring/trace/page/time")
    public String autoMachineTracePageTime(String deviceId, ModelMap modelMap,String startTime,String endTime,ConsoleContext consoleContext){
        modelMap.put("deviceId",deviceId);
        modelMap.put("endTime",endTime);
        modelMap.put("startTime",startTime);
        if(consoleContext.isPhone()){
            return "console/map/phone/auto_monitoring_trace_time";
        }
        return "console/map/auto_monitoring_trace_time";
    }
    /**
     * 获取自动驾驶坐标轨迹
     * @return
     */
    @RequestMapping("/console/machine/monitoring/ponit/trace/json")
    public @ResponseBody HttpResult buildAutoMachineTrace(GetAutoMachineTraceReq getAutoMachineTraceReq){
        return HttpResultUtil.buildSuccess(pointRespService.buildAutoMachineTrace(getAutoMachineTraceReq));
    }

    /**
     * ab线json
     * @return
     */
    @RequestMapping("/console/machine/abline/json")
    public @ResponseBody HttpResult abLineRespList(){
        return HttpResultUtil.buildSuccess(pointRespService.abLineRespList());
    }
    /**
     * ab线页面
     * @return
     */
    @RequestMapping("/console/machine/abline/page")
    public String abLineRespPage(){
        return "console/map/auto_machine_abline";
    }


}
